<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>SLCC Demo</title>
    <script src="../dist/slcc-browser-wasm.js"></script>
    <script src="./demo.js"></script>
    <link rel="stylesheet" type="text/css" href="./demo.css" />
    <script>
      // 需要浏览器支持WebAssembly
      // 不能支持本地运行环境 file:///
      // 代价是用户需要额外下载一个2M+的二进制文件
      //
      // demo.html?address=PHSRC://xxxxxxx/;PHSRC_HTTPS://xxxxxxxx/;UsingMultiChannel://;&cid=xxxxx
      // Demo内容，通过querystring获取连接参数
      // 主机参数
      var validParameter = false;
      var query = location.search;
      var queryArr = query.substring(1).split("&");
      var queryParams = {};
      var reg = /PHSRC_(HTTP|HTTPS):\/\/([^\/]+):(\d+)*\//;
      var host;
      var cid;
      var ssl = true;
      var port = 443;

      var queryArr = query.substring(1).split("&");

      for (var i = 0, l = queryArr.length; i < l; i++) {
        var pair = queryArr[i].split("=", 2);

        queryParams[pair[0]] = pair[1];
      }

      if (!queryParams["address"] || !queryParams["cid"]) {
        alert("Missing parameter");
      } else {
        validParameter = true;
      }

      var matches = queryParams["address"].match(reg);
      if (!matches.length || undefined === matches[1]) {
        alert("Invalid address format");
        validParameter = false;
      }

      host = matches[2];
      // 独立部署可以打开以下两行注释，会根据地址适配是否走加密
      //port = matches[3];
      //ssl  = -1 != matches[1].indexOf('HTTPS');
      cid = queryParams["cid"];
    </script>
    <style>
      html,
      body {
        height: 100%;
        padding: 0;
        margin: 0;
        background: #000;
        text-align: center;
      }

      #wrapper {
        margin: 0 auto;
      }
    </style>
  </head>

  <body>
    <!-- 此为Demo页面，更详细内容请参看SDK文档 -->
    <!-- 桌面视图的父节点 -->
    <div id="wrapper"></div>

    <div class="msg-placeholder" id="msg">
      <div class="loading" id="loading-animate">
        <span></span><span></span><span></span><span></span><span></span>
      </div>
      <span id="msg-text" class="msg-text">正在加载程序...</span>
    </div>

    <script>
      addEventListener("load", function() {
        if (validParameter) {
          // START 向日葵远程桌面
          var client = new SunloginControl.Client({
            // 客户端

            // SDK
            host: host, // FROM SDK: PHSRC://11840.slp2p-live01.oray.net:4118/;PHSRC_HTTPS://11840.slp2p-live01.oray.net:443/;UsingMultiChannel://; 只要主机名
            embed: true, // SDK 传true
            ssl: ssl, // slp2p 线上没有证书，如果是独立服务器且SSL配置齐全，可打开
            cid: cid, // FROM SDK: CID
            port: port, // 缺省443

            debug: true // 控制台日志输出，生产环境请关闭debug
          });

          SunloginControl.Wasm.preload().then(() => {
            console.log("Load wasm");
            updateMessage("开始连接");

            // 初始化桌面视图
            var wrapper = document.getElementById("wrapper");

            var imgInfo = null;

            client
              .connect() // 客户端连接开始
              .then(() => {
                // disconnect 应该放在连接成功之后监听，连接失败直接通过catch捕获
                // 否则连接过程中可能会有若干次disconnect事件
                client.on("disconnect", function() {
                  wrapper.style.display = "none";
                  updateMessage("连接断开", false);
                  view = null;
                  delete view;
                });

                var view = new SunloginControl.Wasm(wrapper);

                // 连接桌面插件
                const desktop = new SunloginControl.Plugin.Desktop({
                  quality: 10
                });
                var framesCount = (totalBytes = 0);
                client.connectPlugin(desktop);

                updateMessage("连接成功，等待桌面图像");

                // imageinfo 桌面图像信息
                desktop.on("imageinfo", info => {
                  view.setImageInfo(info);
                });

                desktop.on("screen", count => {
                  //console.log("屏幕数量：" + count);
                });

                desktop.on("session", sessions => {
                  //console.log("系统会话：", sessions);
                });

                // 视频数据流事件
                // stream Uint8Array H264视频流
                // info object {
                //   "streamId": 10201,
                //   "width": 1920,
                //   "height": 1080,
                //   "frameId": 0,
                //   "length": 41021,
                //   "type": 0
                // }
                desktop.on("stream", (stream, info) => {
                  // framesCount++;
                  // totalBytes += info.length;
                  desktop.sendDecodeFinishMessage(++framesCount)
                  view.decode(stream, info);

                  hideMessage();
                  // desktop.sendFrameControlMessage(framesCount, totalBytes);
                });

                // 传输鼠标（触摸）& 键盘(Win)事件，不传输任何主控端事件，即为观看
                desktop.transportMouseEvent(wrapper);
                desktop.transportKeyBoardEvent(wrapper);
              })
              .catch(e => {
                console.log("Error occured: ", e);
                updateMessage("连接失败: " + e, false);
              });

            // 页面unload关闭客户端连接
            window.onunload = function() {
              client.disconnect();
            };
          });
        }
      });
    </script>
  </body>
</html>
